package org.ourgrid.worker.business.requester;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.interfaces.to.OutgoingHandle;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.worker.business.controller.FileTransferController;
import org.ourgrid.worker.business.dao.WorkerDAOFactory;
import org.ourgrid.worker.business.messages.WorkerControllerMessages;
import org.ourgrid.worker.request.OutgoingTransferCompletedRequestTO;

public class OutgoingTransferCompletedRequester implements RequesterIF<OutgoingTransferCompletedRequestTO> {

	public List<IResponseTO> execute(OutgoingTransferCompletedRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		OutgoingHandle handle = request.getHandle();
		
		File fileCompleted = WorkerDAOFactory.getInstance().getFileTransferDAO().getUploadingFile(handle);
		String senderPublicKey = request.getSenderPublicKey();
		
		if(fileCompleted == null) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getWorkerReceivesAnOutgoingFileTransferCompletedWithUnknownHandleMessage(
							handle.getId(), request.getAmountUploaded(), senderPublicKey), LoggerResponseTO.WARN));
			return responses;
		}
		
		String filePath = fileCompleted.getAbsolutePath();
		
		if(WorkerDAOFactory.getInstance().getWorkerStatusDAO().isFileTransferErrorState()) {
			
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getWorkerWithErrorReceivesAnOutgoingFileTransferCompletedMessage(filePath, handle.getId(), request.getAmountUploaded(), senderPublicKey), LoggerResponseTO.WARN));
			return responses;
		}
	
		FileTransferController.getInstance().outgoingTransferCompleted(handle, request.getAmountUploaded(), responses);
		
		return responses;
	}

}
